<?php

namespace app\api\controller;
use app\admin\controller\Db;
	use app\common\model\Commission;
	use app\common\model\CommissionLog;
	use app\common\model\DscConfig;
    use app\common\model\GoldLog;
    use app\common\model\CouponLog;
	use app\common\model\Coupon;
    use app\common\model\Job;
	use app\common\model\Member;
	use app\home\controller\Showpintuan;
	use think\Lang;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 登录控制器
 */
class Login extends MobileMall
{

    public function _initialize()
    {
        parent::_initialize();
        Lang::load(APP_PATH . 'home/lang/' . config('default_lang') . '/login.lang.php');
    }

    /**
     * @api {POST} api/Login/index 用户登录
     * @apiVersion 1.0.0
     * @apiGroup Login
     *
     * @apiParam {String} username 用户名
     * @apiParam {String} password 密码
     * @apiParam {String} client_type 客户端类型 android wap wechat ios windows jswechat
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {String} result.token  用户token
     * @apiSuccess {Object} result.info 用户信息
     * @apiSuccess {Int} result.info.member_id  用户ID
     * @apiSuccess {String} result.info.member_name  用户名称
     * @apiSuccess {String} result.info.member_truename  真实姓名
     * @apiSuccess {String} result.info.member_avatar  头像
     * @apiSuccess {Int} result.info.member_points  积分
     * @apiSuccess {String} result.info.member_email  邮箱
     * @apiSuccess {String} result.info.member_mobile  手机号
     * @apiSuccess {String} result.info.member_qq  QQ
     * @apiSuccess {String} result.info.member_ww  旺旺
     * @apiSuccess {String} result.seller_token  卖家token
     * @apiSuccess {Object} result.seller_info  卖家信息
     * @apiSuccess {Int} result.seller_info.store_id  店铺ID
     * @apiSuccess {Int} result.seller_info.member_id  用户ID
     * @apiSuccess {Int} result.seller_info.seller_id  卖家ID
     * @apiSuccess {String} result.seller_info.seller_name  卖家账号
     * @apiSuccess {String} result.seller_info.store_avatar  店铺头像
     * @apiSuccess {Int} result.seller_info.is_platform_store  是否自营店铺 0否1是
     * @apiSuccess {Int} result.seller_info.storeclass_id  店铺分类ID
     */
    public function index()
    {
        $username = input('param.username');
        $password = input('param.password');
        $client = input('param.client_type');

        if (empty($username) || empty($password) || !in_array($client, $this->client_type_array)) {
            ds_json_encode(10001,lang('param_error'));
        }

        $member_model = model('member');

        $array = array();
        $array['member_name'] = $username;
        $array['member_password'] = md5($password);
        $member_info = $member_model->getMemberInfo($array);


        if (empty($member_info) && preg_match('/^0?(13|15|17|18|14)[0-9]{9}$/i', $username)) {//根据会员名没找到时查手机号
            $array = array();
            $array['member_mobile'] = $username;
            $array['member_password'] = md5($password);
            $member_info = $member_model->getMemberInfo($array);
        }

        if (empty($member_info) && (strpos($username, '@') > 0)) {//按邮箱和密码查询会员
            $array = array();
            $array['member_email'] = $username;
            $array['member_password'] = md5($password);
            $member_info = $member_model->getMemberInfo($array);
        }

        if($member_info && $member_info['member_account_status'] == 0){
            ds_json_encode(10001, '当前账户已注销！');
        }

        if (is_array($member_info) && !empty($member_info)) {
            if (!$member_info['member_state']) {
                ds_json_encode(10001, lang('login_index_account_stop'));
            }
            $this->getUserToken($member_info,$client);
        }
        else {
            ds_json_encode(10001,lang('password_error'));
        }
    }
    /*
    * 手机短信登录
    */
    public function mobileLogin()
    {
        $client = input('param.client_type');
        $phone = input('param.phone');
        if (empty($phone) || !in_array($client, $this->client_type_array)) {
            ds_json_encode(10001,lang('param_error'));
        }
        $member_mobile['member_mobile'] = $phone;
        $member_name['member_name'] = $phone;
        $member_model = model('member');
        $member_info = $member_model->getMemberInfo($member_name);
        if(!$member_info){
            $member_info = $member_model->getMemberInfo($member_mobile);
        }
        if($member_info){
            if(!$member_info['member_account_status']){
                ds_json_encode(10001, '当前账户已注销！');
            }
            $this->getUserToken($member_info,$client);
        }else{
            ds_json_encode(10001,lang('login_fail'));
        }
        
    }
    /*
    *微信登录
    */
    public function wxLogin()
    {
        $APPID = 'wxdcf0530e77857815';
        $AppSecret = 'ebb3d092c039226f10a4c8894acaa20b';

        $code = input('param.code');
        $client = input('param.client_type');
        $phone = input('param.phone');
        $member_wxunionid = input('param.member_openid');

        if (empty($member_wxunionid) || !in_array($client, $this->client_type_array)) {
            ds_json_encode(10001,lang('param_error'));
        }

        $member_model = model('member');
        if($member_wxunionid && empty($phone)){//拿openid去查询，存在直接登录，不存在要求输入手机号
            $memberArray['member_wxunionid'] = $member_wxunionid;
            $member_info = $member_model->getMemberInfo($memberArray);
            if(empty($member_info)){
                ds_json_encode(10002,'微信标识不存在');
            }else{
                if($member_info['member_account_status'] == 0){
                    ds_json_encode(10002,'微信标识不存在'); //如果仅仅通过微信标识查询的，已经注销的账号 ，需输入手机号
                    //ds_json_encode(10001, '当前账户已注销！');//
                }
                $this->getUserToken($member_info,$client);
            }
        }
        if($member_wxunionid && $phone && empty($code)){//如果微信id查不到会员信息，则需要绑定手机号，如果该手机号已存在，直接绑定微信号，如果不存在，则进行注册
            $memberArray = array();
            $memberArray['member_wxunionid'] = $member_wxunionid;
            $memberArray['member_name'] = $phone;
            $member_info = $member_model->getMemberInfo($memberArray);

            if(empty($member_info)){

                $memberArray1['member_wxunionid'] = $member_wxunionid;
                $memberArray1['member_mobile'] = $phone;
                $member_info = $member_model->getMemberInfo($memberArray1);
            }
            if(empty($member_info)){//如果微信id和手机号检索不到信息，则手机号去检索，有信息则绑定微信。没有则注册
                $member_data['member_name'] = $memberArray['member_name'];
                $member_info = $member_model->getMemberInfo($member_data);

                if(empty($member_info)){
                    $member_data2['member_mobile'] = $phone;
                    $member_info = $member_model->getMemberInfo($member_data2);

                }
                if($member_info){//绑定微信
                    if($member_info['member_account_status'] == 0){
                        //用手机号查询一下是否已经重新注册了
                        $newMemberArray = array();
                        $newMemberArray['member_name'] = $phone;
                        $newMember_info = $member_model->getMemberInfo($newMemberArray);
                        if($newMember_info && $newMember_info['member_id'] != $member_info['member_id']){
                            $trem['member_id'] = $newMember_info['member_id'];
                            $updateData['member_wxunionid'] = $member_wxunionid;
                            Member::where($trem)->update($updateData);
                        }else{
                            $this->wx_register($memberArray, $client);//账号注销的话 直接注册
                            //ds_json_encode(10001, '当前账户已注销！');
                        }


                    }

                    $trem['member_id'] = $member_info['member_id'];
                    $updateData['member_wxunionid'] = $member_wxunionid;
                    Member::where($trem)->update($updateData);

                }
            }
            if($member_info){//存在信息，则直接登录成功
                if($member_info['member_account_status'] == 0){
                    //用手机号查询一下是否已经重新注册了
                    $newMemberArray = array();
                    $newMemberArray['member_name'] = $phone;
                    $newMember_info = $member_model->getMemberInfo($newMemberArray);
                    if($newMember_info && $newMember_info['member_id'] != $member_info['member_id']){
                        $trem['member_id'] = $newMember_info['member_id'];
                        $updateData['member_wxunionid'] = $member_wxunionid;
                        Member::where($trem)->update($updateData);
                    }else{
                        $this->wx_register($memberArray, $client);//账号注销的话 直接注册
                        //ds_json_encode(10001, '当前账户已注销！');
                    }
                }
                $this->getUserToken($member_info,$client);
            }else{//注册
                $this->wx_register($memberArray, $client);
            }
        }
        if(!$member_wxunionid && $code){
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$APPID}&secret={$AppSecret}&code={$code}&grant_type=authorization_code";
            $res = http_request($url);
            if(!$res->openid){
                ds_json_encode(10001,lang('wx_error'));
            }
            $openId = $res->openid;
            $array = array();
            $array['member_wxunionid'] = $openId;
            $member_info = $member_model->getMemberInfo($array);
            if($member_info['member_name']){//存在信息，则直接登录成功
                $this->getUserToken($member_info,$client);
            }else{//返回给客户端，需输入手机号，验证码验证手机号，进行绑定注册
                ds_json_encode(10003,['member_wxunionid'=>$openId, 'error_message'=>'请绑定手机号']);
            }
        }
        ds_json_encode(10001,lang('param_error'));
    
    }
    
    /*
    *微信登录 注册用
    */
    private function wx_register($memberArray, $client)
    {
        /*print_r($memberArray);
        exit;
member_wxunionid*/
        $member_model = model('member');
        $register_info = array();
        $register_info['member_golds'] = $this->getMemberGolds();
        $coupon = $this->getMemberCoupons();//获取优惠券赠送优惠券
        $register_info['member_name'] = $memberArray['member_name'];
        $register_info['member_wxunionid'] = $memberArray['member_wxunionid'];
        $register_info['member_mobile'] = $memberArray['member_name'];//注册时，用手机号注册的，所以会员信息手机号要补充
        $register_info['member_mobilebind'] = 1;
        $register_info['member_password'] = 123456;//初始密码默认123456

        $member_info = $member_model->register($register_info);
        if (!isset($member_info['error'])) {
            $token = $member_model->getBuyerToken($member_info['member_id'], $member_info['member_name'], $client);
            if ($token) {
                if($coupon){//赠送优惠券
                    if($coupon['coupon_count']){//赠送的优惠券张数
                        $count = $coupon['coupon_count'];
                        for ($i=0; $i < $count; $i++) { 
                            $coupon_id = Coupon::addNum($member_info['member_id'], $coupon['coupon_num'], $coupon['coupon_limit']);
                            if($coupon_id){
                                CouponLog::addLogNum($coupon_id,$member_info['member_id'],3,'注册送优惠券'.$coupon['coupon_num']."元");
                            }
                        }
                    } 
                }
                GoldLog::addLogNum($member_info['member_id'], $register_info['member_golds'],3,'注册送金币赠送'.$register_info['member_golds']."个");
                ds_json_encode(10000, '',array('info'=>$this->getMemberUser($member_info),'username' => $member_info['member_name'], 'userid' => $member_info['member_id'],'token' => $token));
            }
            else {
                ds_json_encode(10001,lang('login_usersave_regist_fail'));
            }
        }
        else {
            ds_json_encode(10001,$member_info['error']);
        }
    }
    public function get_inviter(){
        $inviter_id=intval(input('param.inviter_id'));
        $member=db('member')->where('member_id',$inviter_id)->field('member_id,member_name')->find();
        ds_json_encode(10000, '',array('member' => $member));
    }
   

    /**
     * @api {POST} api/Login/register 普通注册
     * @apiVersion 1.0.0
     * @apiGroup Login
     *
     * @apiParam {String} username 用户名
     * @apiParam {String} password 密码
     * @apiParam {String} password_confirm 确认密码
     * @apiParam {String} email 邮箱
     * @apiParam {Int} inviter_id 推荐人id
     * @apiParam {String} client 客户端类型
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Int} result.userid  用户ID
     * @apiSuccess {String} result.username  用户名称
     * @apiSuccess {String} result.token  用户token
     * @apiSuccess {Object} result.info 用户信息
     * @apiSuccess {Int} result.info.member_id  用户ID
     * @apiSuccess {Object} result.info.member_name  用户名称
     * @apiSuccess {Object} result.info.member_truename  真实姓名
     * @apiSuccess {Object} result.info.member_avatar  头像
     * @apiSuccess {Object} result.info.member_points  积分
     * @apiSuccess {Object} result.info.member_email  邮箱
     * @apiSuccess {Object} result.info.member_mobile  手机号
     * @apiSuccess {Object} result.info.member_qq  QQ
     * @apiSuccess {Object} result.info.member_ww  旺旺
     */
    public function register()
    {
        $username = input('param.username');
        $password = input('param.password');
        $password_confirm = input('param.password_confirm');
        $email = input('param.email');
        $client = input('param.client');
        $inviter_id = intval(input('param.inviter_id')) ?? 0;
	    $captcha = input('param.code');//短信
        if(empty($username) || empty($password) || empty($password_confirm)){
            ds_json_encode(10002,lang('请填写完整参数'));
        }
        if(empty($captcha)){
	        ds_json_encode(10001,lang('验证码不能为空'));
        }

        if($password_confirm != $password){
            ds_json_encode(10001,lang('login_register_password_not_same'));
        }

	    $condition = array();
	    $condition['smslog_phone'] = $username;
	    $condition['smslog_captcha'] = $captcha;
	    $condition['smslog_type'] = 1;//注册
	    $smslog_model = model('smslog');
	    $sms_log = $smslog_model->getSmsInfo($condition);
	    if (empty($sms_log) || ($sms_log['smslog_smstime'] < TIMESTAMP - 1800)) {//半小时内进行验证为有效
		    ds_json_encode(10001,lang('dynamic_code_expired'));
	    }
        $member_model = model('member');
        $register_info = array();
        $register_info['member_name'] = $username;
        $register_info['member_mobile'] = $username;//注册时，用手机号注册的，所以会员信息手机号要补充
        $register_info['member_mobilebind'] = 1;
        $register_info['member_password'] = $password;
        $register_info['member_email'] = $email;
        //添加奖励积分
        if($inviter_id){
            $member_info = db('member')->where('member_id', $inviter_id)->find();
            if(empty($member_info)){
                ds_json_encode(10003,lang('推荐人不存在'));
            }
            $register_info['inviter_id'] = $inviter_id;
        }
        if(empty($client)){
        	$client = get_device_type_data();
        }

        $register_info['member_golds'] = $this->getMemberGolds();//获取金币赠送金币
        $coupon = $this->getMemberCoupons();//获取优惠券赠送优惠券

        $member_info = $member_model->register($register_info);
        if (!isset($member_info['error'])) {
            $token = $member_model->getBuyerToken($member_info['member_id'], $member_info['member_name'], $client);
            if ($token) {

                if($coupon){//赠送优惠券
                    if($coupon['coupon_count']){//赠送的优惠券张数
                        $count = $coupon['coupon_count'];
                        for ($i=0; $i < $count; $i++) { 
                            $coupon_id = Coupon::addNum($member_info['member_id'], $coupon['coupon_num'], $coupon['coupon_limit']);
                            if($coupon_id){
                                CouponLog::addLogNum($coupon_id,$member_info['member_id'],3,'注册送优惠券'.$coupon['coupon_num']."元");
                            }
                        }
                    } 
                }
	            GoldLog::addLogNum($member_info['member_id'], $register_info['member_golds'],3,'注册送金币赠送'.$register_info['member_golds']."个");
                ds_json_encode(10000, '',array('info'=>$this->getMemberUser($member_info),'username' => $member_info['member_name'], 'userid' => $member_info['member_id'],'token' => $token));
            }
            else {
                ds_json_encode(10001,lang('login_usersave_regist_fail'));
            }
        }
        else {
            ds_json_encode(10001,$member_info['error']);
        }
    }


	/**
	 * @api {POST} api/Login/register 普通注册
	 * @apiVersion 1.0.0
	 * @apiGroup Login
	 *
	 * @apiParam {String} username 用户名
	 * @apiParam {String} password 密码
	 * @apiParam {String} password_confirm 确认密码
	 * @apiParam {String} email 邮箱
	 * @apiParam {Int} inviter_id 推荐人id
	 * @apiParam {String} client 客户端类型
	 *
	 * @apiSuccess {String} code 返回码,10000为成功
	 * @apiSuccess {String} message  返回消息
	 * @apiSuccess {Object} result  返回数据
	 * @apiSuccess {Int} result.userid  用户ID
	 * @apiSuccess {String} result.username  用户名称
	 * @apiSuccess {String} result.token  用户token
	 * @apiSuccess {Object} result.info 用户信息
	 * @apiSuccess {Int} result.info.member_id  用户ID
	 * @apiSuccess {Object} result.info.member_name  用户名称
	 * @apiSuccess {Object} result.info.member_truename  真实姓名
	 * @apiSuccess {Object} result.info.member_avatar  头像
	 * @apiSuccess {Object} result.info.member_points  积分
	 * @apiSuccess {Object} result.info.member_email  邮箱
	 * @apiSuccess {Object} result.info.member_mobile  手机号
	 * @apiSuccess {Object} result.info.member_qq  QQ
	 * @apiSuccess {Object} result.info.member_ww  旺旺
	 */
	public function commission_register()
	{
		$username = input('param.username');
		$password = input('param.password');
		$password_confirm = input('param.password_confirm');
		$email = input('param.email');
		$captcha = input('param.code');//短信
		$client = input('param.client');
		$job_id = intval(input('param.job_id'));
		$inviter_id = intval(input('param.inviter_id'));


        if(empty($username) || empty($password) || empty($password_confirm) || empty($inviter_id)){
            $this->error('请填写完整参数', 10002);
        }

		if(!$job_id){
			$this->error("参数错误",null,405);
		}
		$job=Job::get($job_id);
		if(!$job){
			$this->error("参数错误",null,404);
		}
		if($password_confirm!=$password){
			ds_json_encode(10001,lang('login_register_password_not_same'));
		}

		$condition = array();
		$condition['smslog_phone'] = $username;
		$condition['smslog_captcha'] = $captcha;
		$condition['smslog_type'] = 1;//注册
		$smslog_model = model('smslog');
		$sms_log = $smslog_model->getSmsInfo($condition);
		if (empty($sms_log) || ($sms_log['smslog_smstime'] < TIMESTAMP - 1800)) {//半小时内进行验证为有效
			ds_json_encode(10001,lang('dynamic_code_expired'));
		}
		$member_model = model('member');
		$register_info = array();
		$register_info['member_name'] = $username;
		$register_info['member_password'] = $password;
		$register_info['member_email'] = $email;
		//添加奖励积分
		if($inviter_id){
			$register_info['inviter_id'] = $inviter_id;
		}
		if(empty($client)){
			$client=get_device_type_data();
		}
		$register_info['member_golds']=$this->getMemberGolds();
        $coupon = $this->getMemberCoupons();//获取优惠券赠送优惠券
		$member_info = $member_model->register($register_info);
		if (!isset($member_info['error'])) {
			$token = $member_model->getBuyerToken($member_info['member_id'], $member_info['member_name'], $client);
			if ($token) {
				$c_data=[
					'job_uid'=>$job['uid'],
					'job_id'=>$job_id,
					'order_id'=>$job['order_id'],
					'user_id'=>$inviter_id,
					'inviter_user_id'=>$member_info['member_id'],
					'money'=>$job['commission'],
					'status'=>0,
					'create_time'=>time(),
					'update_time'=>time(),
				];
				CommissionLog::create($c_data,true);

                if($coupon){//赠送优惠券
                    if($coupon['coupon_count']){//赠送的优惠券张数
                        $count = $coupon['coupon_count'];
                        for ($i=0; $i < $count; $i++) { 
                            $coupon_id = Coupon::addNum($member_info['member_id'], $coupon['coupon_num'], $coupon['coupon_limit']);
                            if($coupon_id){
                                CouponLog::addLogNum($coupon_id,$member_info['member_id'],3,'注册送优惠券'.$coupon['coupon_num']."元");
                            }
                        }
                    } 
                }

				GoldLog::addLogNum($member_info['member_id'], $register_info['member_golds'],3,'注册送金币赠送'.$register_info['member_golds']."个");
				ds_json_encode(10000, '注册成功');
			}
			else {
				ds_json_encode(10001,lang('login_usersave_regist_fail'));
			}
		}
		else {
			ds_json_encode(10001,$member_info['error']);
		}
	}

    /**
     * @api {POST} api/Login/register 分享注册
     * @apiVersion 1.0.0
     * @apiGroup Login
     *
     * @apiParam {String} username 用户名
     * @apiParam {String} password 密码
     * @apiParam {String} password_confirm 确认密码
     * @apiParam {String} email 邮箱
     * @apiParam {Int} inviter_id 推荐人id
     * @apiParam {String} client 客户端类型
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Int} result.userid  用户ID
     * @apiSuccess {String} result.username  用户名称
     * @apiSuccess {String} result.token  用户token
     * @apiSuccess {Object} result.info 用户信息
     * @apiSuccess {Int} result.info.member_id  用户ID
     * @apiSuccess {Object} result.info.member_name  用户名称
     * @apiSuccess {Object} result.info.member_truename  真实姓名
     * @apiSuccess {Object} result.info.member_avatar  头像
     * @apiSuccess {Object} result.info.member_points  积分
     * @apiSuccess {Object} result.info.member_email  邮箱
     * @apiSuccess {Object} result.info.member_mobile  手机号
     * @apiSuccess {Object} result.info.member_qq  QQ
     * @apiSuccess {Object} result.info.member_ww  旺旺
     */
    public function share_register()
    {
        $username = input('param.username');
        $password = input('param.password');
        $password_confirm = input('param.password_confirm');
        $email = input('param.email');
        $captcha = input('param.code');//短信
        $client = input('param.client');
        $inviter_id = intval(input('param.inviter_id'));


        if(empty($username) || empty($password) || empty($password_confirm) || empty($inviter_id)){
            $this->error('请填写完整参数', 10002);
        }

        if($password_confirm!=$password){
            ds_json_encode(10001,lang('login_register_password_not_same'));
        }

        $condition = array();
        $condition['smslog_phone'] = $username;
        $condition['smslog_captcha'] = $captcha;
        $condition['smslog_type'] = 1;//注册
        $smslog_model = model('smslog');
        $sms_log = $smslog_model->getSmsInfo($condition);
        if (empty($sms_log) || ($sms_log['smslog_smstime'] < TIMESTAMP - 1800)) {//半小时内进行验证为有效
            ds_json_encode(10001,lang('dynamic_code_expired'));
        }
        $member_model = model('member');
        $register_info = array();
        $register_info['member_name'] = $username;
        $register_info['member_password'] = $password;
        $register_info['member_email'] = $email;
        //添加奖励积分
        if($inviter_id){
            $register_info['inviter_id'] = $inviter_id;
        }
        if(empty($client)){
            $client=get_device_type_data();
        }
        $register_info['member_golds']=$this->getMemberGolds();
        $coupon = $this->getMemberCoupons();//获取优惠券赠送优惠券
        $member_info = $member_model->register($register_info);
        if (!isset($member_info['error'])) {
            $token = $member_model->getBuyerToken($member_info['member_id'], $member_info['member_name'], $client);
            if ($token) {
                if($coupon){//赠送优惠券
                    if($coupon['coupon_count']){//赠送的优惠券张数
                        $count = $coupon['coupon_count'];
                        for ($i=0; $i < $count; $i++) { 
                            $coupon_id = Coupon::addNum($member_info['member_id'], $coupon['coupon_num'], $coupon['coupon_limit']);
                            if($coupon_id){
                                CouponLog::addLogNum($coupon_id,$member_info['member_id'],3,'注册送优惠券'.$coupon['coupon_num']."元");
                            }
                        }
                    } 
                }

                GoldLog::addLogNum($member_info['member_id'], $register_info['member_golds'],3,'注册送金币赠送'.$register_info['member_golds']."个");
                ds_json_encode(10000, '注册成功');
            }
            else {
                ds_json_encode(10001,lang('login_usersave_regist_fail'));
            }
        }
        else {
            ds_json_encode(10001,$member_info['error']);
        }
    }

    public function h5_login()
    {
        return $this->fetch();
    }
    public function h5_register()
    {
        return $this->fetch();
    }
	/**
	 * 短信动态码
	 */
	public function get_captcha() {
		header("Content-Type: text/html;charset=utf-8");
		$sms_mobile = input('param.sms_mobile');
		if (strlen($sms_mobile) == 11) {
			$log_type = input('param.type'); //短信类型:1为注册,2为登录,3为找回密码

			$member_model = model('member');
			$member = $member_model->getMemberInfo(array('member_mobile' => $sms_mobile));
			$sms_captcha = rand(100000, 999999);
			$log_msg = '【' . config('site_name') . '】'.lang('ds_you_in').'' . date("Y-m-d");
			switch ($log_type) {
				case '1':
					if (config('sms_register') != 1) {
						echo lang('system_obile_registration_function');
						exit;
					}
					if (!empty($member) && $member['member_account_status'] == 1) {
						//检查手机号是否已被注册
						echo lang('change_another_number');;
						exit;
					}
					$log_msg .= lang('register_member_dynamic_code') . $sms_captcha . '。';
					break;
				case '2':
					if (config('sms_login') != 1) {
						echo lang('enable_mobile_phone_login');
						exit;
					}
					if (empty($member)) {
						//检查手机号是否已绑定会员
						echo lang('check_correct_number');
						exit;
					}
					$log_msg .= lang('application_login_dynamic_code'). $sms_captcha . '。';
					break;
				case '3':
					if (config('sms_password') != 1) {
						echo lang('mobile_back_password');
						exit;
					}
					if (empty($member)) {
						//检查手机号是否已绑定会员
						echo lang('check_correct_number');
						exit;
					}
					$log_msg .= lang('reset_password_dynamic_code') . $sms_captcha . '。';
					break;
				default:
					echo lang('param_error');
					exit;
					break;
			}

			$smslog_model = model('smslog');
			$result = $smslog_model->sendSms($sms_mobile,$log_msg,$log_type,$sms_captcha,$member['member_id'],$member['member_name']);
			if($result['state']){
				ds_json_encode(10000,"短信发送成功");
			}else{
				ds_json_encode(10001,$result['message']);
				echo $result['message'];
				exit;
			}
		} else {
			ds_json_encode(10001,lang('phone_length_incorrect'));
			//echo lang('phone_length_incorrect');
			//exit;
		}
	}


    /**
     * @api {POST} api/Login/bind 绑定用户
     * @apiVersion 1.0.0
     * @apiGroup Login
     *
     * @apiParam {Int} type 类型 1注册 0绑定
     * @apiParam {String} user 用户名
     * @apiParam {String} username 用户名
     * @apiParam {String} password 密码
     * @apiParam {String} password2 确认密码
     * @apiParam {String} email 邮箱
     * @apiParam {String} openid openid
     * @apiParam {String} unionid unionid
     * @apiParam {String} nickname 昵称
     * @apiParam {String} headimgurl 头像
     * @apiParam {String} from 来源 wx微信
     * @apiParam {Int} inviter_id 推荐人id
     * @apiParam {String} client_type 客户端类型 android wap wechat ios windows jswechat
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Int} result.userid  用户ID
     * @apiSuccess {String} result.username  用户名称
     * @apiSuccess {String} result.token  用户token
     * @apiSuccess {Object} result.info 用户信息
     * @apiSuccess {Int} result.info.member_id  用户ID
     * @apiSuccess {Object} result.info.member_name  用户名称
     * @apiSuccess {Object} result.info.member_truename  真实姓名
     * @apiSuccess {Object} result.info.member_avatar  头像
     * @apiSuccess {Object} result.info.member_points  积分
     * @apiSuccess {Object} result.info.member_email  邮箱
     * @apiSuccess {Object} result.info.member_mobile  手机号
     * @apiSuccess {Object} result.info.member_qq  QQ
     * @apiSuccess {Object} result.info.member_ww  旺旺
     */
    public function bind() {
        $member_model = model('member');
        $type = input('param.type');
        $user = input('param.user');
        $email = input('param.email');
        $password = input('param.password');
        $password2 = input('param.password2');
        $from = input('param.from');
        $openid = input('param.openid');
        $unionid = input('param.unionid');
        $nickname = input('param.nickname');
        $headimgurl = input('param.headimgurl');
        $client = input('param.client_type');
        $inviter_id = intval(input('param.inviter_id'));
        $reg_info = array();
        $data = array(
            'member_name' => $user,
            'member_password' => $password,
        );
        switch ($from) {
            case 'wx':
                $reg_info = array(
                    'member_wxopenid' => $openid, #开发者帐号唯一标识,与公众号标识不同
                    'member_wxunionid' => $unionid,
                    'nickname' => $nickname,
                    'headimgurl' => $headimgurl,
                );
                $data = array_merge($data, array(
                    'member_wxopenid' => $openid,
                    'member_wxunionid' => $unionid,
                    'member_wxinfo' => serialize($reg_info),
                ));
                break;
            case 'qq':
                $reg_info = array(
                    'member_qqopenid' => $openid, #开发者帐号唯一标识,与公众号标识不同
                    'member_qqunionid' => $unionid,
                    'nickname' => $nickname,
                    'headimgurl' => $headimgurl,
                );
                $data = array_merge($data, array(
                    'member_qqopenid' => $openid,
                    'member_qqunionid' => $unionid,
                    'member_qqinfo' => serialize($reg_info),
                ));
                break;
            case 'sina':
                $reg_info = array(
                    'member_sinaopenid' => $openid, #开发者帐号唯一标识,与公众号标识不同
                    'member_sinaunionid' => $unionid,
                    'nickname' => $nickname,
                    'headimgurl' => $headimgurl,
                );
                $data = array_merge($data, array(
                    'member_sinaopenid' => $openid,
                    'member_sinaunionid' => $unionid,
                    'member_sinainfo' => serialize($reg_info),
                ));
                break;
        }


        if ($type == 1) {//注册
            $data = array_merge($data, array(
                'member_email' => $email,
                'member_nickname' => $reg_info['nickname'],
                'inviter_id' => $inviter_id,
            ));
            
            $login_validate = validate('member');
            if (!$login_validate->scene('register')->check($data)) {
                ds_json_encode(10001, $login_validate->getError());
            }
            $member_info = $member_model->register($data);
            if (!isset($member_info['error'])) {
                $token = $member_model->getBuyerToken($member_info['member_id'], $member_info['member_name'], $client);
                if ($token) {
                    ds_json_encode(10000, '', array('info' => $this->getMemberUser($member_info), 'username' => $member_info['member_name'], 'userid' => $member_info['member_id'], 'token' => $token));
                } else {
                    ds_json_encode(10001, lang('login_fail'));
                }
//                $headimgurl = $reg_info['headimgurl'];
//                $avatar = @copy($headimgurl, BASE_UPLOAD_PATH . '/' . ATTACH_AVATAR . "/avatar_" . $member_info['member_id'] . ".jpg");
//                if ($avatar) {
//                    $member_model->editMember(array('member_id' => $member_info['member_id']), array('member_avatar' => "avatar_" . $member_info['member_id'] . ".jpg"));
//                }
            } else {
                ds_json_encode(10001, $member_info['error']);
            }
        } else {//绑定
            $login_validate = validate('member');
            if (!$login_validate->scene('login')->check($data)) {
                ds_json_encode(10001, $login_validate->getError());
            }
            $map = array(
                'member_name' => $data['member_name'],
                'member_password' => md5($data['member_password']),
            );
            $member_info = $member_model->getMemberInfo($map);
            if ($member_info) {
            	if($from == 'wx'){
		            $member=$member_model->where('member_wxunionid',$unionid)->find();
		            if($member){
			            ds_json_encode(10001,"此微信已经存在");
		            }
	            }elseif($from == 'qq'){
		            $member=$member_model->where('member_qqopenid',$openid)->find();
		            if($member){
			            ds_json_encode(10001,"此qq已经存在");
		            }
	            }elseif($from == 'sina'){
		            $member=$member_model->where('member_sinaopenid',$openid)->find();
		            if($member){
			            ds_json_encode(10001,"此新浪账号已经存在");
		            }
	            }
                $member_model->editMember(array('member_id' => $member_info['member_id']), array('member_wxunionid' => $data['member_wxunionid'],'member_wxopenid' => $openid, 'member_wxinfo' => $data['member_wxinfo']));
            } else {
                ds_json_encode(10001, lang('password_error'));
            }
            $token = $member_model->getBuyerToken($member_info['member_id'], $member_info['member_name'], $client);
            if ($token) {
                ds_json_encode(10000, '', array('info' => $this->getMemberUser($member_info), 'username' => $member_info['member_name'], 'userid' => $member_info['member_id'], 'token' => $token));
            } else {
                ds_json_encode(10001, lang('login_fail'));
            }
        }
    }
    
    /**
     * @api {POST} api/Login/get_user_by_openid 第三方通过openid获取用户信息
     * @apiVersion 1.0.0
     * @apiGroup Login
     *
     * @apiParam {String} from 来源 wx微信 qq sina新浪
     * @apiParam {String} openid openid
     * @apiParam {String} unionid unionid
     * @apiParam {String} avatar 头像
     * @apiParam {String} nickname 昵称
     * @apiParam {Int} inviter_id 推荐人ID
     * @apiParam {String} client_type 客户端类型 android wap wechat ios windows jswechat
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {String} result.token  用户token
     * @apiSuccess {Object} result.info 用户信息
     * @apiSuccess {Int} result.info.member_id  用户ID
     * @apiSuccess {String} result.info.member_name  用户名称
     * @apiSuccess {String} result.info.member_truename  真实姓名
     * @apiSuccess {String} result.info.member_avatar  头像
     * @apiSuccess {Int} result.info.member_points  积分
     * @apiSuccess {String} result.info.member_email  邮箱
     * @apiSuccess {String} result.info.member_mobile  手机号
     * @apiSuccess {String} result.info.member_qq  QQ
     * @apiSuccess {String} result.info.member_ww  旺旺
     * @apiSuccess {String} result.seller_token  卖家token
     * @apiSuccess {Object} result.seller_info  卖家信息
     * @apiSuccess {Int} result.seller_info.store_id  店铺ID
     * @apiSuccess {Int} result.seller_info.member_id  用户ID
     * @apiSuccess {Int} result.seller_info.seller_id  卖家ID
     * @apiSuccess {String} result.seller_info.seller_name  卖家账号
     * @apiSuccess {String} result.seller_info.store_avatar  店铺头像
     * @apiSuccess {Int} result.seller_info.is_platform_store  是否自营店铺 0否1是
     * @apiSuccess {Int} result.seller_info.storeclass_id  店铺分类ID
     */
    public function get_user_by_openid(){
        $from = input('param.from');
        $openid = input('param.openid');
        $unionid = input('param.unionid');
        $client = input('param.client_type');
        $avatar = input('param.avatar');
        $nickname = input('param.nickname');
        $inviter_id = intval(input('param.inviter_id'));
 
        if(!$from || !$openid || !in_array($client, $this->client_type_array)){
            ds_json_encode(10001, lang('param_error'));
        }
        $condition=array();
        switch($from){
            case 'wx':
                if($unionid){
                    $condition['member_wxunionid']=$unionid;
                }else{
                    $condition['member_wxopenid']=$openid;
                }
                break;
            case 'qq':
                $condition['member_qqopenid']=$openid;
                break;
            case 'sina':
                $condition['member_sinaopenid']=$openid;
                break;
            default:
                ds_json_encode(10001, lang('param_error'));
                break;
        }
        $member_model=model('member');
        $member_info = $member_model->getMemberInfo($condition);
        if(!$member_info){
            //自动注册
            if(config('auto_register')) {//如果开启了自动注册
                $logic_connect_api = model('connectapi', 'logic');
                //注册会员信息 返回会员信息
                $reg_info = array(
                    'member_wxopenid' => $openid,
                    'member_wxunionid' => $unionid,
                    'nickname' => $nickname,
                    'inviter_id'=>$inviter_id,#推荐人ID
//                    'headimgurl' => $avatar,#提高体验暂时不对图片进行处理
                );
                $wx_member = $logic_connect_api->wx_register($reg_info, $from);
                if (!empty($wx_member)) {
                    $token = $member_model->getBuyerToken($wx_member['member_id'], $wx_member['member_name'], $client);
                    ds_json_encode(10000, '',array('token'=>$token,'info'=>$this->getMemberUser($wx_member)));
                } else {
                     ds_json_encode(10001, lang('login_usersave_regist_fail'));
                }
            }else{
                ds_json_encode(10000);//没有用户，进入绑定页
            }
        }else{
            if($member_info['member_state']==0){
                ds_json_encode(10001, lang('member_state_0'));
            }
            $this->getUserToken($member_info,$client);
        }
    }
    
    private function getUserToken($member_info,$client){
        
        $member_model=model('member');
            $token = $member_model->getBuyerToken($member_info['member_id'], $member_info['member_name'], $client);
            if ($token) {
                $result = array();
                $result['token'] = $token;
                $result['info'] = $this->getMemberUser($member_info);
                $result['username']= $member_info['member_name'];
                $result['userid']= $member_info['member_id'];
                //是否有卖家账户
                $seller_model = model('seller');
                $seller_info = $seller_model->getSellerInfo(array('member_id' => $member_info['member_id']));
                if($seller_info){
                    $token = Sellerlogin::_get_seller_token($seller_info['seller_id'], $seller_info['seller_name'], $client);
                    if(!$token){
                        ds_json_encode(10001,lang('login_fail'));
                    }
                    //读取店铺信息
                    $store_model = model('store');
                    $store_info = $store_model->getStoreInfoByID($seller_info['store_id']);
                    $result['seller_token'] = $token;
                    $result['seller_info'] = $this->getSellerUser($seller_info,$store_info);
                }
                ds_json_encode(10000, '',$result);
            }
            else {
                ds_json_encode(10001,lang('login_fail'));
            }
    }

	/**
	 * 注册时获取金币
	 * @return Showpintuan
	 */
    private function getMemberGolds(){
    	$reg_give_gold_type=$this->getConfig('reg_give_gold_type');
    	if($reg_give_gold_type == 1){
		    $gold=$this->getConfig('reg_give_gold_num');
	    }else{
		    $gold=0;
	    }

		return  $gold;
    }
    /**
     * 注册时获取优惠券
     * @return Showpintuan
     */
    private function getMemberCoupons(){
        $reg_give_coupon_type=$this->getConfig('reg_give_coupon_type');
        if($reg_give_coupon_type == 1){
            $coupon['coupon_num']=$this->getConfig('reg_give_coupon_num');
            $coupon['coupon_limit']=$this->getConfig('reg_give_coupon_limit');
            $coupon['coupon_count']=$this->getConfig('reg_give_coupon_count');
        }else{
            $coupon=0;
        }

        return  $coupon;
    }
	/**
	 * 获取配置的值
	 * @param string $class
	 * @return mixe
	 */
	private function getConfig($class=''){
		$value=DscConfig::where('name',$class)->value('value');
		if($class == 'comment_table'){
			$value=explode(',',$value);
		}
		return $value;
	}
}

?>
